package com.jgp.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

/**
 * 项目   jgp-cloud-parent
 * 作者   loufei
 * 时间   2019/1/30
 */
@Order(400)
@ConditionalOnProperty(prefix = "jgp.ws", name = "enabled", havingValue = "true")
@Configuration //@Configuration注解表明它是一个Spring配置类
@EnableWebSocketMessageBroker //通过@EnableWebSocketMessageBroker 注解启用WebSocket消息处理，由消息代理支持。
public class WebsocketConfiguration implements WebSocketMessageBrokerConfigurer {
    
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        /*
         * 该registerStompEndpoints()方法注册“/serverStatus”端点，
         * 启用SockJS后备选项，以便在WebSocket不可用时可以使用替代传输。
         * SockJS客户端将尝试连接到“/serverStatus”并使用可用的最佳传输（websocket，xhr-streaming，xhr-polling等）。
         * setAllowedOrigins: 允许跨域
         */
        registry.addEndpoint("/jgp-ws-server").setAllowedOrigins("*").withSockJS();
        registry.addEndpoint("/jgp-wxs-server").setAllowedOrigins("*");
    }
    
    /**
     * 配置消息代理
     * @param registry
     */
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        ThreadPoolTaskScheduler te = new ThreadPoolTaskScheduler();
        te.setPoolSize(1);
        te.setThreadNamePrefix("heartbeat-thread-");
        te.initialize();
        registry.enableSimpleBroker("/topic","/user").setHeartbeatValue(new long[]{5000,5000}).setTaskScheduler(te); // 调用enableSimpleBroker()一个简单的基于内存的消息代理，将问候消息带回以“/ receive”为前缀的客户端
        registry.setUserDestinationPrefix("/user");
        //        registry.setApplicationDestinationPrefixes("/app"); //为绑定了@MessageMapping注解方法的消息指定“/ app”前缀,该前缀将用于定义所有消息映射
    }
}
